package com.hc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.domain.Permission;
import com.hc.domain.RolePermission;
import com.hc.service.PermissionService;
import com.hc.service.RolePermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.Null;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/rolePermission")
public class RolePermissionController {

    @Resource
    private RolePermissionService rolePermissionService;
    @Resource
    private PermissionService permissionService;

    @PostMapping
    public Result<Null> create(@RequestBody RolePermission rolePermission) {
        boolean res = rolePermissionService.save(rolePermission);
        return res ? ResultUtil.success("添加成功") : ResultUtil.fail("添加失败");
    }

    @PutMapping
    public Result<Null> updateById(@RequestBody RolePermission rolePermission) {
        boolean res = rolePermissionService.updateById(rolePermission);
        return res ? ResultUtil.success("更新成功") : ResultUtil.fail("更新失败");
    }

//    @DeleteMapping("{id}")
//    public Result<Null> removeById(@PathVariable Serializable id) {
//        boolean res = rolePermissionService.removeById(id);
//        return res ? ResultUtil.success("删除成功") : ResultUtil.fail("删除失败");
//    }

    @GetMapping("{id}")
    public Result<List<Permission>> getById(@PathVariable Serializable id) {
        QueryWrapper<RolePermission> queryWrapper=new QueryWrapper<>();
        List<Permission>  permissionList = new ArrayList<>();
        queryWrapper.eq("role_id",id);
        List<RolePermission> rolePermissionList = rolePermissionService.list(queryWrapper);
        for (RolePermission res:rolePermissionList) {
            if (res != null) {
                Integer permissionId = res.getPermissionId();
                Permission permission = permissionService.getById(permissionId);
                permissionList.add(permission);
            } else {
                return ResultUtil.success("查询失败");
            }
        }
        return ResultUtil.<List<Permission>>success("查询成功").setData(permissionList);
    }


}